<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 *  Games Controller
 *
 * @package XGO CMS v2.0
 * @subpackage Games
 * @author Manh Nguyen - 30/07/2012
 * @link http://sunsoft.vn
 */
class Newhot extends CI_Controller {
    /**
     * Contrust class
     *
     * @access public
     */
    public function __construct() {
        parent::__construct();

		$this->load->library('smarty3', '', 'smarty');
        
        require_once(APPPATH . 'modules/backend/autoload.php');        
        
        $this->load->library('login_manager');
        require_once(APPPATH . 'modules/backend/info.php');
        
        $this->load->helper('formatdate');

        $this->login_manager->check_role('games');
        $this->load->language('backend');
        
        //$this->lang->load('backend','vietnamese');
        $this->smarty->assign('language', $this->lang);
        $this->smarty->assign('message', $this->session->flashdata('message'));
        $this->smarty->assign('error_message', $this->session->flashdata('error_message'));
        require_once(APPPATH . 'modules/backend/kcfinder.php');
    }

    /**
     * index function, show jquery grid
     *
     * @access public
     * @param null
     * @return void
     */
    function index() {    
//        $parameters = $this->uri->ruri_to_assoc();
//
//        if (isset($parameters['id'])) {
//            $id = intval($parameters['id']);
//            if ($id > 0) {
//                $this->session->set_userdata('search_id', $id);
//            }
//        }

        $css_files = array(base_url() . 'data/jscripts/jqgrid/css/ui.jqgrid.css');

        $js_files = array(
            base_url() . 'data/jscripts/jqgrid/i18n/grid.locale-vi.js',
            base_url() . 'data/jscripts/jqgrid/jquery.jqGrid.min.js'
        );

        require_once(APPPATH . 'modules/backend/history.php');
        $items = new Items_model();

        //load parameters and initialize grid
        $jqgrid = array();

        $jqgrid['id'] = 'jqgrid';
        $jqgrid['pager'] = 'pagered';
        $jqgrid['caption'] = $items->localize_label('manager');
        $jqgrid['url_metadata'] = site_url($this->router->directory . 'newhot/jqgrid_jsoninit');
        $jqgrid['url_data'] = site_url($this->router->directory . 'newhot/jqgrid_jsondata');
        //$jqgrid['url_create'] = site_url($this->router->directory . 'newhot/create');
        $jqgrid['url_edit'] = site_url($this->router->directory . 'newhot/edit');
        $jqgrid['url_delete'] = site_url($this->router->directory . 'newhot/delete');

        $this->smarty->assign('jqgrid', $jqgrid);

        $jqgrid_init = $this->smarty->get_contents('template/backend/js/jqgrid_2');
        $js_text = array($jqgrid_init);

        $this->smarty->assign('css_files', $css_files);
        $this->smarty->assign('js_files', $js_files);
        $this->smarty->assign('js_text', $js_text);
        $this->smarty->assign('title', $items->localize_label('manager'));
        
        // view
        $this->smarty->view('backend/items/jqgrid', 'grid');
        $this->smarty->display('template/backend/admin');
    }

    /**
     * Create news
     *
     * @access public
     */

    public function edit() {

        $language       =   new Language_model();

        $this->smarty->assign('language', $language);
        
        $items = new Items_model();
        
        $opnew = $items->option_stNew();
        $opbestbuy = $items->option_stBestBuy();
        $this->smarty->assign(array('optionNew'=>$opnew,'optionBestBuy'=>$opbestbuy));
        
        if ($this->input->server('REQUEST_METHOD') === 'GET') {
            $parameters = $this->uri->ruri_to_assoc(3);

            if (isset($parameters['id'])) {
                $id = intval($parameters['id']);
            } else {
                $id = 0;
            }
           $items->get_by_id($id);

            //-------------------
            if ($items->exists()) {
                $this->smarty->assign('items', $items);
                $this->smarty->view('backend/items/edit', 'main_content');
                $this->smarty->display('template/backend/admin');
            } else {
                $this->session->set_flashdata('error_message', $this->lang->line('not_found')/* 'Bài viết này không tồn tại xin vui lòng kiểm tra lại.' */);
                redirect(site_url('auth/newhot'));
            }
        } else {// save update 
            $this->load->library('form_validation');
            $this->form_validation->set_rules('title', $this->lang->line('title'), 'trim|required|max_length[150]');

            $id = $this->input->post('id');
            $items->get_by_id($id);
            if ($this->form_validation->run() == TRUE) {
                $this->_save(site_url('auth/newhot/'), $items);
            } else {
                $this->smarty->assign('items', $items);
                $this->smarty->view('backend/items/edit', 'main_content');
                $this->smarty->display('template/backend/admin');
            }
        }
    }

    private function _save($uri, $items) {
        // Begin transaction
        $items->trans_begin();
        
        $now = date("Y:m:d H:i:s");
       
        if($items->stNew != $this->input->post('stNew'))
        {
            $items->stNew = $this->input->post('stNew');
            $items->dateNewInsert = $now;
        }
        
        if($items->stBestBuy != $this->input->post('stBestBuy'))
        {
            $items->stBestBuy = $this->input->post('stBestBuy');
            $items->dateBestBuyInsert = $now;
        }
        
        $items->save();
        
        $exists = $items->exists();
        // Attempt to save user
        // Check status of transaction
        if ($items->trans_status() === FALSE) {
            // Transaction failed, rollback
            $items->trans_rollback();

            // Add error message
            $u->error_message('transaction', 'The transaction failed to save (insert)');
        } else {
            // Transaction successful, commit
            $items->trans_commit();
            // $this->lang->load('model_Games_model','vietnamese');
            if ($exists) {
                $this->session->set_flashdata('message', $items->localize_label('edit_success')/* 'Đã cập nhật dữ liệu thành công.' */);
            } else {
                $this->session->set_flashdata('message', $items->localize_label('create_success')/* 'Đã lưu dữ liệu thành công.' */);
            }
            redirect($uri);
        }
        // Show all errors
        $error = $items->error->string;

        $this->session->set_flashdata('message', $error);
        edirect($uri);
    }

    /**
     * delete function, delete exists object
     *
     * @access public
     * @param id of object in url
     * @return void
     */
    function delete() {

        $url = 'newhot';

        $parameters = $this->uri->ruri_to_assoc();

        if (isset($parameters['id'])) {
            $ids = explode('-',$parameters['id']);
            foreach($ids as $value)
            {
                $id[] = intval($value);
            }
        } else {
            $id = 0;
        }

        if ($id <= 0) {
            $this->session->set_flashdata('error_message', $this->lang->line('not_found'));
            redirect($this->router->directory . $url);
        }

        foreach($id as $value){
            $items = new Items_model();
            $items->where('id', $value);
            $items->get(1);

            if ($items->id <= 0) {
                $this->session->set_flashdata('error_message', $this->lang->line('not_found'));
                redirect($this->router->directory . $url);
            }

            $result = $items->delete();
            if ($result === TRUE) {
                $this->session->set_flashdata('message', $items->localize_label('delete_success'));
            } else {
                $this->session->set_flashdata('message', $items->localize_label('delete_fail'));
            }
        }
        redirect($this->router->directory . $url);
    }

    /**
     * init function, get para for jquery grid via ajax
     *
     * @access public
     * @param null
     * @return array in json encode
     */
    function jqgrid_jsoninit() {
        if (IS_AJAX) {
            $items = new Items_model();
            $metadata = $items->jqgrid_metadata();//print_r($metadata);exit;
            echo json_encode($metadata);
        }
    }

    /**
     * data function, get data for jquery grid via ajax
     *
     * @access public
     * @param null
     * @return array in json encode
     */
    function jqgrid_jsondata() {
        
        if (IS_AJAX) {
            $search = $this->input->post('_search');
            $filters = json_decode($this->input->post('filters'));
            $order = $this->input->post('sidx');
            $order_direct = $this->input->post('sord');
            $page = intval($this->input->post('page'));
            $num_per_page = intval($this->input->post('rows'));

//            $relative_search = array(
//                'category' => array(
//                    'search' => 'id',
//                    'include' => array('id', 'title')
//                )
//            );

            $this->load->helper('jqgrid');

            $items = jqgrid_search(new Items_model(), $search, $filters, $order, $order_direct, $page, $num_per_page);

            $paged = $items->paged;
            $responce = new Stdclass();
            $responce->page = $paged->current_page; //curent page
            $responce->total = $paged->total_pages; //total page
            $responce->records = $paged->total_rows; //total record
            $i = 0;

            foreach ($items as $item) {
                $isLeaf = TRUE;
                $responce->rows[$i]['cell'] = array(
                    // Field
                    $item->id,
                    $item->itemID,
                    $item->title,
                    $item->get_stNew(),
                    $item->dateNewInsert,
                    $item->get_stBestBuy(),
                    $item->dateBestBuyInsert,
                    // Format
                    NULL,
                    NULL,
                    $isLeaf,
                    false
                );
                $i++;
            }
            //print_r($responce); exit;
            echo json_encode($responce);
        }
    }

}

